<template>
    <div class="app-container">
        <el-row :gutter="24">
            <!--表格搜索栏-->
            <el-col :span="24" :xs="24">
                <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
                    <el-form-item label="设备编码" prop="equipmentCode">
                        <el-input v-model="queryParams.equipmentCode" placeholder="请输入设备编码" clearable size="small"
                            style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="设备名称" prop="equipmentName">
                        <el-input v-model="queryParams.equipmentName" placeholder="请输入设备名称" clearable size="small"
                            style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="设备类型" prop="equipmentType">
                        <treeselect v-model="queryParams.equipmentType" :options="sblxOptions"
                            :normalizer="normalizerSb" style="width: 240px" placeholder="选择设备类型" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <!-- 头部按钮 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['shebei:taizhang:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport"
                    v-hasPermi="['shebei:taizhang:import']">导入</el-button>
                <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['shebei:taizhang:export']">导出</el-button>
                <el-link type="info" style="font-size:12px;margin:0 0 0 15px" @click="importTemplate">下载模板</el-link>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="sbList">
            <el-table-column label="设备名称" align="center" prop="equipmentName" />
            <el-table-column label="设备编码" align="center" prop="equipmentCode" :show-overflow-tooltip="true" />
            <el-table-column label="设备类型" align="center" prop="equipmentType" :show-overflow-tooltip="true" />
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <span>{{scope.row.status==="0"?'正常':'关闭'}}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" />
            <el-table-column label="ip地址" align="center" prop="ipAddress" :show-overflow-tooltip="true" />
            <el-table-column label="端口" align="center" prop="port" :show-overflow-tooltip="true" />
            <el-table-column label="上级设备" align="center" prop="superiorEquipment" :show-overflow-tooltip="true" />
            <el-table-column label="设备所在地" align="center" prop="equipmentLocation" width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="采购价格" align="center" prop="procurementPrice" :show-overflow-tooltip="true" />
            <el-table-column label="更新时间" align="center" prop="updateTime" :show-overflow-tooltip="true" />
            <el-table-column label="入场时间" align="center" prop="approachTime" :show-overflow-tooltip="true" />
            <el-table-column label="启用时间" align="center" prop="activeTime" :show-overflow-tooltip="true" />
            <el-table-column label="责任人" align="center" prop="responsible" width="120">
                <template slot-scope="scope">
                    <span>{{personOptionsRender(scope.row)}}</span>
                </template>
            </el-table-column>
            <el-table-column label="责任部门" align="center" prop="department" width="120" />
            <el-table-column label="备注" align="center" prop="remark" width="120" />
            <el-table-column label="出厂编码/序列" align="center" prop="factoryCode" width="120" />
            <el-table-column label="型号/规格" align="center" prop="specification" width="120" />
            <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['shebei:taizhang:edit']">修改</el-button>

                    <el-button v-if="scope.row.userId !== 1" size="mini" type="text" icon="el-icon-delete"
                        @click="handleDelete(scope.row)" v-hasPermi="['shebei:taizhang:del']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />
        <!-- 添加或修改参数配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="closeDialog"   >
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="设备编码" prop="equipmentCode">
                            <el-input v-model="form.equipmentCode" placeholder="请输入设备编码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="设备名称" prop="equipmentName">
                            <el-input v-model="form.equipmentName" placeholder="请输入设备名称型" maxlength="11" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="设备类型" prop="equipmentType">
                            <treeselect v-model="form.equipmentType" :options="sblxOptions" :normalizer="normalizerSb"
                                placeholder="选择设备类型" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="责任人" prop="responsible">
                            <el-select v-model="form.responsible" filterable placeholder="请选择责任人">
                                <el-option v-for="dict in personOptions" :key="dict.userId" :label="dict.nickName"
                                    :value="dict.userId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="责任部门" prop="department">
                            <treeselect v-model="form.department" :options="deptOptions" :normalizer="normalizer"
                                placeholder="选择责任部门" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12"> <el-form-item label="状态" prop="status">
                            <el-select v-model="form.status" placeholder="请选择状态" clearable size="small"
                                style="width: 200px">
                                <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                                    :value="dict.dictValue" />
                            </el-select>
                        </el-form-item> </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="启用日期" prop="activeTime">
                            <el-date-picker v-model="form.activeTime" type="date" placeholder="选择启用日期"
                                value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入场时间" prop="approachTime">
                            <el-date-picker v-model="form.approachTime" type="date" placeholder="选择入场时间"
                                value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="ip地址" prop="ipAddress">
                            <el-input v-model="form.ipAddress" placeholder="请输入ip地址" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="端口" prop="port">
                            <el-input v-model="form.port" placeholder="请输入端口" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="设备所在地" prop="equipmentLocation">
                            <el-input v-model="form.equipmentLocation" placeholder="请输入设备所在地" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="上级设备" prop="superiorEquipment">
                            <el-input v-model="form.superiorEquipment" placeholder="请输入上级设备" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="规格/型号" prop="specification">
                            <el-input v-model="form.specification" placeholder="请输入规格/型号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="出场编号/序号" prop="factoryCode">
                            <el-input v-model="form.factoryCode" placeholder="请输入出场编号/序号" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="采购价格" prop="procurementPrice">
                            <el-input v-model="form.procurementPrice" placeholder="请输入采购价格" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">
                    <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
                </div>
                <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

    import { listDept, listDeptExcludeChild } from "@/api/system/dept";
    import { getPersonList } from "@/api/stores/person";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    import Treeselect from "@riophae/vue-treeselect";
    import IconSelect from "@/components/IconSelect";
    import { addSb, getSbList, updateSb, delSb, exportSb, treeselectSb, importTemplate } from "@/api/shebei";
    import { getToken } from "@/utils/auth";
    export default {
        name: "Taizhang",
        components: { Treeselect },
        data() {
            return {
                // 遮罩层
                loading: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 表格数据
                sbList: null,
                // 弹出层标题
                title: "",
                // 部门树选项
                deptOptions: [],
                // 是否显示弹出层
                open: false,
                // 部门名称
                deptName: undefined,
                // 默认密码
                initPassword: undefined,
                // 日期范围
                dateRange: [],
                // 状态数据字典
                statusOptions: [],
                // 设备类型字典
                sbOptions: [],
                // 设备类型选项
                sblxOptions: [],
                // 责任人选项
                personOptions: [],
                // 岗位选项
                postOptions: [],
                // 角色选项
                roleOptions: [],
                // 表单参数
                form: {},
                defaultProps: {
                    children: "children",
                    label: "label",
                },
                // 用户导入参数
                upload: {
                    // 是否显示弹出层（用户导入）
                    open: false,
                    // 弹出层标题（用户导入）
                    title: "",
                    // 是否禁用上传
                    isUploading: false,
                    // 是否更新已经存在的用户数据
                    updateSupport: 0,
                    // 设置上传的请求头部
                    headers: { Authorization: "Bearer " + getToken() },
                    // 上传的地址
                    url: process.env.VUE_APP_BASE_API + "/equipment/ledger/importDataAdd",
                },
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                },
                // 表单校验
                rules: {
                    equipmentCode: [
                        { required: true, message: "设备编码不能为空", trigger: "blur" },
                    ],
                    equipmentName: [
                        { required: true, message: "设备名称不能为空", trigger: "blur" },
                    ],
                    department: [
                        { required: true, message: "责任部门不能为空", trigger: "blur" },
                    ],

                },
            };
        },

        created() {
            this.getList();
            this.getDicts("equipment_ledger").then((response) => {
                this.statusOptions = response.data;
            });
            //部门树
            listDept().then(response => {
                this.deptOptions = this.handleTree(response.data, "deptId");
            });
            this.getSbTreeselect()
            this.getPersonList()
            this.personOptionsRender()
        },
        methods: {
            //渲染责任人
            personOptionsRender(row) {
                const res= this.personOptions.map(item => {
                    if (item.userId === Number(row.responsible)) {
                        return item.nickName
                    }
                })
                return res.filter(Boolean)[0]
            },
            /** 查询设备列表 */
            getList() {
                this.loading = true;
                getSbList(this.queryParams).then(
                    (response) => {
                        this.sbList = response.rows;
                        this.total = response.total;
                        this.loading = false;
                    }
                );
            },
            /** 查询角色（责任人）列表 */
            getPersonList() {
                getPersonList(this.queryParams).then(
                    (response) => {
                        this.personOptions = response.rows;
                    }
                );
            },
            /** 转换部门数据结构 */
            normalizer(node) {
                if (node.children && !node.children.length) {
                    delete node.children;
                }
                return {
                    id: node.deptId,
                    label: node.deptName,
                    children: node.children
                };
            },
            /** 转换设备类型数据结构 */
            normalizerSb(node) {
                if (node.children && !node.children.length) {
                    delete node.children;
                }
                return {
                    id: node.typeId,
                    label: node.typeName,
                    children: node.children
                };
            },
            /** 查询设备类型下拉树结构 */
            getSbTreeselect() {
                treeselectSb().then((response) => {
                    this.sblxOptions = response.data;
                });
            },


            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
                this.getList()
            },
            closeDialog() {
                this.getList()

            },
            // 表单重置
            reset() {
                this.form = {};
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                // this.queryParams.page = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.resetForm("queryForm");
                this.handleQuery();
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加设备";

            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.open = true;
                this.title = "修改设备";
                this.form = row
                const res= this.personOptions.map(item => {
                    if (item.userId === Number(row.responsible)) {
                        return item.nickName
                    }
                })
                this.form.responsible=res.filter(Boolean)[0]
            },
            /** 提交按钮 */
            submitForm: function () {
                this.$refs["form"].validate((valid) => {
                    if (valid) {
                        if (this.title === '修改设备') {
                            updateSb(this.form).then((response) => {
                                if (response.code === 200) {
                                    this.msgSuccess("修改成功");
                                    this.open = false;
                                    this.getList();
                                }
                            });
                        } else {
                            addSb(this.form).then((response) => {
                                if (response.code === 200) {
                                    this.msgSuccess("新增成功");
                                    this.open = false;
                                    this.getList();
                                }
                            });
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                this.$confirm(
                    '是否确认删除设备编码为"' + row.equipmentCode + '"的数据项?',
                    "警告",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(function () {
                        return delSb(row.id);
                    })
                    .then(() => {
                        this.getList();
                        this.msgSuccess("删除成功");
                    })
                    .catch(function () { });
            },
            /** 导出按钮操作 */
            handleExport() {
                const queryParams = this.queryParams;
                this.$confirm("是否确认导出所有设备台账数据项?", "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(function () {
                        return exportSb(queryParams);
                    })
                    .then((response) => {
                        this.download(response.msg);
                    })
                    .catch(function () { });
            },
            /** 导入按钮操作 */
            handleImport() {
                this.upload.title = "设备台账导入";
                this.upload.open = true;
            },
            /** 下载模板操作 */
            importTemplate() {
                importTemplate().then((response) => {
                    this.download(response.msg);
                });
            },
            // 文件上传中处理
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
            },
            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                this.upload.open = false;
                this.upload.isUploading = false;
                this.$refs.upload.clearFiles();
                this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
                this.getList();
            },
            // 提交上传文件
            submitFileForm() {
                this.$refs.upload.submit();
            },
        },
    };
</script>